package com.itheima.reggie.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.itheima.reggie.common.BaseContext;
import com.itheima.reggie.common.CustomException;
import com.itheima.reggie.dto.OrdersDto;
import com.itheima.reggie.mapper.OrdersMapper;
import com.itheima.reggie.pojo.*;
import com.itheima.reggie.service.*;
import lombok.SneakyThrows;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.concurrent.atomic.AtomicInteger;

@Service
public class OrdersServiceImpl extends ServiceImpl<OrdersMapper, Orders> implements OrdersService {
    @Resource
    private OrderDetailService orderDetailService;
    @Resource
    private ShoppingCartService shoppingCartService;
    @Resource
    private UserService userService;
    @Resource
    private AddressBookService addressBookService;
    @Resource
    private OrdersMapper ordersMapper;

    /**
     * 用户下单
     * @param orders 订单信息
     */
    @Override
    public void sbumit(Orders orders) {
        //获取当前用户的Id
        Long userId = BaseContext.getCurrentId();
        //查询购物车信息
        List<ShoppingCart> shoppingCarts = shoppingCartService.lambdaQuery()
                .eq(ShoppingCart::getUserId, userId)
                .list();
        if (shoppingCarts == null){
            //购物车为空 不能下单
            throw new CustomException("购物车为空,不能下单");
        }
        //查询用户信息
        User user = userService.getById(userId);

        //查询地址信息
        AddressBook address = addressBookService.getById(orders.getAddressBookId());
        //地址信息不全
        if (address == null){
            throw new CustomException("地址信息不全,无法下单");
        }

        //设置订单信息
        long orderId = IdWorker.getId();
        //定义订单总金额
        AtomicInteger total = new AtomicInteger(0);

        //1. 添加订单详情数据，操作是order_detail表（多条数据）        由购物车的数据决定
        // TODO 补全List集合中的数据
        List<OrderDetail> orderDetails = new ArrayList<>();

        for (ShoppingCart cart : shoppingCarts) {
            //创建一个OrderdDetail
            OrderDetail orderDetail = new OrderDetail();
            orderDetail.setOrderId(orderId);//订单id
            orderDetail.setNumber(cart.getNumber());//设置数量
            orderDetail.setDishFlavor(cart.getDishFlavor());//口味
            orderDetail.setDishId(cart.getDishId());//菜品id
            orderDetail.setSetmealId(cart.getSetmealId());//套餐id
            orderDetail.setName(cart.getName());//名称
            orderDetail.setImage(cart.getImage());//图片
            orderDetail.setAmount(cart.getAmount());//金额 单价
            //计算总金额     单价*数量
            total.addAndGet( cart.getAmount().multiply(new BigDecimal( cart.getNumber())).intValue());
            //TODO 往集合中添加orderDetail对象
            orderDetails.add(orderDetail);
        }
        orderDetailService.saveBatch(orderDetails);
        //2.  添加订单数据，操作是orders表（一条数据）
        //TODO 补全Order对象的数据
        orders.setOrderTime(LocalDateTime.now());//下单时间
        orders.setCheckoutTime(LocalDateTime.now());//支付时间
        orders.setStatus(2);//状态 订单状态 1待付款，2待派送，3已派送，4已完成，5已取消
        orders.setUserId(userId);//用户id
        orders.setId(orderId);
        orders.setNumber(String.valueOf(orderId));//订单编号
        orders.setUserName(user.getName());
        orders.setConsignee(address.getConsignee());//收获人
        orders.setPhone(address.getPhone()); //收货人手机号
        orders.setAddress( (address.getProvinceName() == null?"":address.getProvinceName())
                + ( address.getCityName() == null?"":address.getCityName())
                + ( address.getDistrictName() == null?"":address.getDistrictName())
                + ( address.getDetail()==null?"":address.getDetail()) );//收获地址
        orders.setAmount(new BigDecimal(total.get()));// 总金额

        //向订单表中插入数据
        this.save(orders);

        //清空购物车
        shoppingCartService.lambdaUpdate()
                .eq(ShoppingCart::getUserId, userId)
                .remove();
    }

    /**
     * 订单分页查询
     */
    @Override
    public Page<OrdersDto> userPage(Page<OrdersDto> ordersPage, Long userId) {
        //用户id

        return ordersMapper.userPage(ordersPage, userId);
    }

    /**
     * 后台查询订单
     * @param number 查询条件
     * @param beginTime 起始时间
     * @param endTime 结束时间
     * @return 查询结果
     */
    @Override
    @SneakyThrows
    public Page<Orders> ordersPage(Page<Orders> ordersPage, Long number, String beginTime, String endTime) {

        Date end = null;
        Date begin = null;
        if (beginTime != null && endTime != null) {
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            begin = sdf.parse(beginTime);
            end = sdf.parse(endTime);
        }
        LambdaQueryWrapper<Orders> queryWrapper = Wrappers.lambdaQuery(Orders.class)
                .like(number != null, Orders::getNumber, number)
                .between(beginTime != null, Orders::getOrderTime, begin, end)
                .orderByDesc(Orders::getOrderTime);
        this.page(ordersPage, queryWrapper);
        return ordersPage;
    }
}
